package cn.genmer.test.security.thread;
 
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
 
public class ThreadTask {
 
    public static void main(String[] args) throws Exception {
        Task1 task1 = new Task1();
        Task2 task2 = new Task2();
        Task3 task3 = new Task3();
        List<Callable<String>> taskList = Arrays.asList(task1,task2,task3);
 
        ExecutorService executorService = Executors.newFixedThreadPool(3);
 
        //提交单个任务
        Future<String> taskFuture = executorService.submit(task1);
 
        //批量提交任务
        List<Future<String>> futureList = executorService.invokeAll(taskList);
 
        for (Future<String> future : futureList) {
            //获取线程返回的结果
            String result = future.get(); //此语句会一直阻塞到结果完成
 
            System.out.println(result);
        }
        executorService.shutdown();
    }
}
 
class Task1 implements Callable<String> {
 
    @Override
    public String call() {
        System.out.println("线程Task1 开始运行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程Task1 结束运行");
        return "1111";
    }
}
 
class Task2 implements Callable<String> {
 
    @Override
    public String call() {
        System.out.println("线程Task2 开始运行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程Task2 结束运行");
        return "2222";
    }
}
 
class Task3 implements Callable<String> {
 
    @Override
    public String call() {
        System.out.println("线程Task3 开始运行");
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("线程Task3 结束运行");
        return "3333";
    }
}